package com.rehome.udp;


import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPReceive {
    private DatagramSocket datagramSocket;
    private DatagramPacket datagramPacket;
    private UDPFrame udpFrame;
    private String sender;

    public UDPReceive(DatagramSocket datagramSocket, DatagramPacket datagramPacket, UDPFrame udpFrame, String sender) {
        this.datagramSocket = datagramSocket;
        this.datagramPacket = datagramPacket;
        this.udpFrame = udpFrame;
        this.sender = sender;
    }

    public void receiveMessages() {
        try {
            while (true) {
                byte[] bytes = new byte[1024];
                datagramPacket = new DatagramPacket(bytes, bytes.length);
                datagramSocket.receive(datagramPacket);
                byte[] data = datagramPacket.getData();
                String string = new String(data, 0, datagramPacket.getLength());
                udpFrame.getTextArea().append("[" + sender + "] : " + string + "\n");
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
            udpFrame.getTextArea().append(sender + "异常\n");
            udpFrame.getTextArea().append(sender + "与客户端连接中断\n");
        } finally {
            udpFrame.getTextArea().append(sender + "关闭\n");
        }
    }
}
